package com.jianye.recycdona.model.fragment.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.jianye.recycdona.R;
import com.jianye.recycdona.control.http.OrderHttp;
import com.jianye.recycdona.model.utils.TimeNumberUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

public class HuishouActivity extends AppCompatActivity {
    private TextView mTvAddress;
    private SharedPreferences sp;
    private String id,name,phone,detai;
    private TextView tvAddress;
    private TimePickerView pvTime;
    private TextView huishou_time;
    private WheelView wheelView;
    private LinearLayout linearLayout;//重量选择容器布局
    private TextView weightTx,AddressInfo;  //重量TextView
    String editStatut;// 订单状态为修改状态


    private String huishouTime;
    private String addressinfo;
    private String weight;
    private SharedPreferences spConfig;
    private String parent_id;//用户唯一标识id
    String thisData;
    private String editdetailAddress,editreserveTime,editweight;
    private Button order_edt;//提交id
    private String edtId;
    public String flag;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huishou);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
            actionBar.hide();
        }




        initFindId();

//        initData();

        initweigh();//重量选择器数据初始化
        initTimePicker();//时间选择器数据初始化


    }



    @SuppressLint("SetTextI18n")
    private void initData() {

        if (!flag.equals("0")){//!=0
            sp= getSharedPreferences("Address", MODE_PRIVATE);//Address 文件名
            id=sp.getString("id","");//地址id
            name=sp.getString("name","");
            phone=sp.getString("phone","");
            detai=sp.getString("detai","");
            tvAddress.setText(name+"\t"+phone+"\n"+detai);
        }

    }


    @Override
    protected void onResume() {
        super.onResume();

        initData();

    }

    private void initFindId() {
        flag="0";
        spConfig = getSharedPreferences("config", MODE_PRIVATE);//confi 文件名
        thisData=getTime(new Date());
        huishou_time=findViewById(R.id.huishou_time_tx);//时间
        linearLayout=findViewById(R.id.weight);//容器
        weightTx=findViewById(R.id.huishou_weight);//重量
        tvAddress=findViewById(R.id.huishou_address);//地址信息
        //修改/提交
        order_edt=findViewById(R.id.order_edt);



        /**
         * 接收传递过来得订单信息
         */
        Intent intent=getIntent();
        edtId=intent.getStringExtra("id");//订单id
        editStatut =intent.getStringExtra("edit");//编辑状态
        editdetailAddress=intent.getStringExtra("editdetail");//订单地址
        editreserveTime=intent.getStringExtra("editreserveTime");//日期
        editweight=intent.getStringExtra("editweight");//重量
        Log.e("editOrder", "---------------------->initData:"+ editStatut + editStatut +editdetailAddress+editreserveTime+editweight);

        //接收地址信息
        if (editStatut !=null&& editStatut.equals("0")&&flag.equals("0")){
            tvAddress.setText(editdetailAddress);
        }
        //接收传递过来的时间和重量，并更新UI
        if (editweight!=null&&editreserveTime!=null){
            weightTx.setText(editweight);
            huishou_time.setText(editreserveTime);
            order_edt.setText("确认修改");
        }

    }

    //返回
    public void Finish(View view) {
        finish();
    }

    //地址选择
    public void addressOnCli(View view) {
        flag="1";//跳转修改地址
        startActivity(new Intent(HuishouActivity.this,AddressListActivity.class));
    }


    //获取当前时间
    public String getTime(Date date) {//可根据需要自行截取数据显示
        Log.e("getTime()", "choice date millis: " + date.getTime());
        @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    //time 时间选择器
    private void initTimePicker() {//Dialog 模式下，在底部弹出

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        //获取当前系统时间
        long timecurrentTimeMillis = System.currentTimeMillis();
        Log.d("test", "  当前时间戳1->:"+timecurrentTimeMillis);

        SimpleDateFormat sdfTwo =new SimpleDateFormat("yyyy-MM-dd-HH-mm:ss", Locale.getDefault());
        String time11 = sdfTwo.format(timecurrentTimeMillis);

        Log.d("test", timecurrentTimeMillis +"  现在的时间11->:" + time11);
        String[] t=time11.split("-");

        Log.d("Year", "----------------initTimePicker: "+t[0]);
        Log.d("Year", "----------------initTimePicker: initTimePicker: "+t[1]);
        Log.d("Year", "----------------initTimePicker: initTimePicker: "+t[2]);
        Log.d("Year", "----------------initTimePicker: initTimePicker: "+t[3]);



        startDate.set(Integer.parseInt(t[0]),Integer.parseInt(t[1])-1,Integer.parseInt(t[2]),Integer.parseInt(t[3]),0);
        endDate.set(Integer.parseInt(t[0]),Integer.parseInt(t[1]),Integer.parseInt(t[2])+5,Integer.parseInt(t[3])+7,0);

        //设置时间
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                Toast.makeText(HuishouActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
                huishou_time.setText(getTime(date));
                Log.i("pvTime", "onTimeSelect");

            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");
                    }
                })
                .setType(new boolean[]{true, true, true, true, true, true})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("请选择上门时间")//标题文字
                .setRangDate(startDate,endDate)
                .setType(new boolean[]{true, true, true, true,false,false})// 默认全部显示
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    // 时间选择
    public void timeOnClick(View view) {
        pvTime.show(view);

    }

    //重量选择器
    private void initweigh() {

       wheelView = findViewById(R.id.wheelview);

        wheelView.setCyclic(false);

        final List<String> mOptionsItems = new ArrayList<>();
        mOptionsItems.add("3kg以下");
        mOptionsItems.add("3kg-10kg(约8件)");
        mOptionsItems.add("10kg-20kg(约28件)");
        mOptionsItems.add("20kg-50kg(约40件)");
        mOptionsItems.add("50kg以上(约80件)");

        wheelView.setAdapter(new ArrayWheelAdapter(mOptionsItems));
        wheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {

                weightTx.setText(mOptionsItems.get(index));
//                Toast.makeText(HuishouActivity.this, "" + mOptionsItems.get(index), Toast.LENGTH_SHORT).show();
            }
        });

    }


    //显示重量
    public void addressKG(View view) {

        linearLayout.setVisibility(View.VISIBLE);

    }

    //隐藏重量
    public void weightvisiblity(View view) {

        linearLayout.setVisibility(View.GONE);
    }

    //提交预约订单
    public void commitOrder(View view) {
        parent_id=spConfig.getString("id","");

        huishouTime=huishou_time.getText().toString().trim();//请选择上门取件时间
        addressinfo=tvAddress.getText().toString().trim();
        weight=weightTx.getText().toString().trim();
        String orderStutas="进行中",reserve="等待取件";
        String ordernum=TimeNumberUtils.getLocalTrmSeqNum();//订单号

        if (addressinfo.equals("请选择或新建地址")){
            Toast.makeText(HuishouActivity.this, "请选择或新建地址", Toast.LENGTH_SHORT).show();
        }else if (huishouTime.equals("请选择上门取件时间")) {
            Toast.makeText(HuishouActivity.this, "请选择上门取件时间", Toast.LENGTH_SHORT).show();
        }else if (weight.equals("请选择旧衣物重量")){
            Toast.makeText(HuishouActivity.this, "请选择旧衣物重量", Toast.LENGTH_SHORT).show();
        }else if (parent_id.equals("")){
            Toast.makeText(HuishouActivity.this, "用户id为空", Toast.LENGTH_SHORT).show();
        } else{


Log.e("OrderInfo", "------->"+parent_id+id+addressinfo+huishouTime+weight+thisData+ordernum+orderStutas+reserve);

            //修改订单
            if (editStatut!=null&&editStatut.equals("0")){

                String code=OrderHttp.getMyOkHttp().putOderInfo(edtId,id,addressinfo,huishouTime,weight);

                if (code.equals("200")){

                    final TextView textView = new TextView(HuishouActivity.this);
                    textView.setText("预约信息修改成功");
                    AlertDialog.Builder inputDialog = new AlertDialog.Builder(HuishouActivity.this);
                    inputDialog.setTitle("提示信息").setView(textView);

                    inputDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).show();
                }

            }else {
                //添加回收

                try {
                    OrderHttp.getMyOkHttp().postOrder(id,ordernum,orderStutas,addressinfo,parent_id,thisData,reserve,huishouTime,weight);
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }

                final TextView textView = new TextView(HuishouActivity.this);
                textView.setText("预约信息提交成功");
                AlertDialog.Builder inputDialog = new AlertDialog.Builder(HuishouActivity.this);
                inputDialog.setTitle("提示信息").setView(textView);

                inputDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).show();

            }



        }





    }
}